﻿namespace FFF.Test.Util.Elastic
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Nest;
    using FFF.Test.Util.Consts;

    /// <summary>
    /// 索引帮助类
    /// </summary>
    public static class ElasticHelper
    {
        /// <summary>
        /// 索引客户端
        /// </summary> 
        public static ElasticClient EsClient { get; set; }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="TModel">插入的对象类型</typeparam>
        /// <param name="models">插入数据的对象</param>
        /// <returns>返回插入结果</returns>
        public static async Task<IBulkResponse> InsertAsync<TModel>(params TModel[] models)
            where TModel : class
        {
            var res = await EsClient.IndexManyAsync<TModel>(models);
            return res;
        }

        /// <summary>
        /// 批量更新
        /// </summary>
        /// <typeparam name="TModel">更新的对象类型</typeparam>
        /// <param name="models">更新的对象</param>
        /// <returns>返回更新的结果</returns>
        public static async Task<IBulkResponse> UpdateAsync<TModel>(params TModel[] models)
          where TModel : class
        {
            var bulkQuest = new BulkRequest() { Operations = new List<IBulkOperation>() };
            foreach (var model in models)
            {
                string id = typeof(TModel).GetProperty("Id").GetValue(model).ToString();
                var operation = new BulkUpdateOperation<TModel, object>(id)
                {
                    Doc = model
                };
                bulkQuest.Operations.Add(operation);
            }

            var result = await EsClient.BulkAsync(bulkQuest);
            return result;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="TModel">文档对象</typeparam>
        /// <param name="ids">文档的ID</param>
        /// <returns>处理结果</returns>
        public static async Task<IBulkResponse> DeleteAsync<TModel>(params string[] ids)
         where TModel : class
        {
            var bulkQuest = new BulkRequest() { Operations = new List<IBulkOperation>() };
            foreach (var id in ids)
            {
                bulkQuest.Operations.Add(new BulkDeleteOperation<TModel>(id));
            }

            var result = await EsClient.BulkAsync(bulkQuest);
            return result;
        }
    }
}